package com.store.app.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.libs.widget.CWToast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.EventType1;
import com.store.app.http.Stores;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.MoneyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 首页收款码页面
 */
public class PaymentActivity extends BaseActivity implements IOnHttpListener {
    private Context context;
    private LinearLayout code_interface, inputkeyboard, achieve;
    private ImageView two_dimension;
    private TextView pay_one, pay_two, pay_three, pay_four, pay_five, pay_six, pay_seven, pay_eight, pay_nine, pay_zero, pay_space, pay_del;
    private TextView show_amount, submit, cancel, payee_amount;
    private String flow_no, security_code, error, money;
    private int QR_WIDTH = 1200, QR_HEIGHT = 1200, subtract = 0, present = 0, condition_amount = 0, number_of_credits = 0, token_conditions = 0, give_number = 0;
    private Handler handler;
    private ProgressDialog progressBar;
    private TextView tvShopName, abrogate;
    private NetRequest netRequest;
    private TextView tv_time;
    private CountDownTimer downtimer;
    private List<String> stringList;
    OnClickListener myListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            money = payee_amount.getText().toString();
            if (money.contains(".")) {
                String[] tempS = money.split("\\.");
                if (tempS.length > 1) {
                    int resultNum = tempS[1].length();
                    if (resultNum > 1) {
                        return;
                    }
                }
            }
            switch (v.getId()) {
                case R.id.pay_space:
                    money = payee_amount.getText().toString();
                    if (!money.contains(".")) {
                        if (money.equals("")) {
                            input_digit("0.");
                        } else {
                            input_digit(".");
                        }
                    }
                    break;

                case R.id.pay_zero:
                    input_digit("0");

                    break;
                case R.id.pay_one:
                    input_digit("1");

                    break;
                case R.id.pay_two:
                    input_digit("2");

                    break;
                case R.id.pay_three:
                    input_digit("3");

                    break;
                case R.id.pay_four:
                    input_digit("4");

                    break;
                case R.id.pay_five:
                    input_digit("5");

                    break;
                case R.id.pay_six:
                    input_digit("6");

                    break;
                case R.id.pay_seven:
                    input_digit("7");

                    break;
                case R.id.pay_eight:
                    input_digit("8");

                    break;
                case R.id.pay_nine:
                    input_digit("9");

                    break;
                default:
                    break;
            }
        }
    };
    private TextView tv_bottom_canel;
    private static final int allTime = 120;
    private int time = allTime;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //注册eventbus
        EventBus.getDefault().register(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.payment);
        stringList = new ArrayList<>();
        initView();
        netRequest = new NetRequest(this);
        ExitApplication.getInstance().addActivity(this);
        context = PaymentActivity.this;
        tv_time = (TextView) findViewById(R.id.tv_time);
        tvShopName = (TextView) findViewById(R.id.tv_shop);
        inputkeyboard = (LinearLayout) findViewById(R.id.inputkeyboard);
        findViewById(R.id.retreat).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                finish();

            }
        });

        show_amount = (TextView) findViewById(R.id.show_amount);
        payee_amount = (TextView) findViewById(R.id.payee_amount);


        two_dimension = (ImageView) findViewById(R.id.two_dimension);

        code_interface = (LinearLayout) findViewById(R.id.code_interface);
        //确认生成收款码
        submit = (TextView) findViewById(R.id.submit);
        submit.setBackgroundResource(R.drawable.border_gray_80ffffff);
        submit.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                money = payee_amount.getText().toString();
                Log.v("zyl", "转化之前：" + money);
                if (!money.equals("")) {
                    double moneyDouble = Double.parseDouble(money);
                    Log.v("zyl", "转化为double的值：" + moneyDouble);

                    String moneyHead2 = "";
                    if (money.length() > 1) {
                        moneyHead2 = money.substring(0, 2);//如果前两位开头是00则提示无效


                        //如果前两位是0开头却不是 0.开头就说明数据无效
                        if (moneyHead2.substring(0, 1).equals("0")) {
                            if (!moneyHead2.equals("0.")) {
                                Toast.makeText(PaymentActivity.this, "输入金额无效",
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                    }
                    Log.v("zyl", "moneyHead2:" + moneyHead2);
                    if (moneyHead2.equals("00")) {
                        Toast.makeText(PaymentActivity.this, "输入金额无效",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (moneyDouble <= 0) {
                        Toast.makeText(PaymentActivity.this, "输入金额无效",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    progressBar = new ProgressDialog(view.getContext());
                    progressBar.setCancelable(true);
                    progressBar.setMessage("生成中...");
                    progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    progressBar.setProgress(0);
                    progressBar.setMax(100);
                    progressBar.show();
                    netRequest.requestReg(1);
//					new registration().start();
                } else {
                    Toast.makeText(PaymentActivity.this, "请输入收款金额",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
        cancel = (TextView) findViewById(R.id.cancel);
        cancel.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });
        pay_one = (TextView) findViewById(R.id.pay_one);
        pay_one.setOnClickListener(myListener);

        pay_two = (TextView) findViewById(R.id.pay_two);
        pay_two.setOnClickListener(myListener);

        pay_three = (TextView) findViewById(R.id.pay_three);
        pay_three.setOnClickListener(myListener);

        pay_four = (TextView) findViewById(R.id.pay_four);
        pay_four.setOnClickListener(myListener);

        pay_five = (TextView) findViewById(R.id.pay_five);
        pay_five.setOnClickListener(myListener);

        pay_six = (TextView) findViewById(R.id.pay_six);
        pay_six.setOnClickListener(myListener);

        pay_seven = (TextView) findViewById(R.id.pay_seven);
        pay_seven.setOnClickListener(myListener);

        pay_eight = (TextView) findViewById(R.id.pay_eight);
        pay_eight.setOnClickListener(myListener);

        pay_nine = (TextView) findViewById(R.id.pay_nine);
        pay_nine.setOnClickListener(myListener);

        pay_zero = (TextView) findViewById(R.id.pay_zero);
        pay_zero.setOnClickListener(myListener);
        pay_space = (TextView) findViewById(R.id.pay_space);
        pay_space.setOnClickListener(myListener);

        pay_del = (TextView) findViewById(R.id.pay_del);
        pay_del.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {


                money = payee_amount.getText().toString();
                int index = money.length();
                if (index != 0) {

                    money = money.substring(0, money.length() - 1);
                    payee_amount.setText(money);
                }
            }
        });
        downtimer = new CountDownTimer(allTime * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.v("zyl", ((millisUntilFinished)) + "");
                time--;
                if (time < 0) {
                    return;
                }
                tv_time.setText(time + "");
//                tv_time.setText((Integer.parseInt(tv_time.getText().toString())-1)+"");
            }

            @Override
            public void onFinish() {
                Log.v("zyl", "倒计时结束了，重新开启注册");
                netRequest.requestReg(1);
                tv_time.setText("0");
            }
        };


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        finish();
                        break;
                    case 1:
                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        Toast.makeText(PaymentActivity.this, error,
                                Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        Toast.makeText(PaymentActivity.this, "请检查本地网络！",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Log.v("zyl", "subtract:" + subtract);
                        if (subtract == 1) {
                            if (Double.parseDouble(money) >= condition_amount) {
//								money=(Double.parseDouble(money)-number_of_credits)+"";
//								Log.v("zyl","money:"+money);
                            }
                        }
                        if (present == 1) {
                            if (Double.parseDouble(money) < token_conditions) {
                                give_number = 0;
                            }
                        }
                        JSONObject data = new JSONObject();
                        try {
                            data.put("type", "R");
                            data.put("security_code", security_code);
                            data.put("flow_no", flow_no);
                            data.put("member_id", MainActivity.member_id);
                            data.put("member_type_key", "stores");
                            Log.v("zyl", "提交 money:" + money);
                            data.put("amount", money);
                            data.put("receive_type", "S");
                            Log.v("zyl", "give_number:" + give_number);
                            data.put("voucher", give_number + "");
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        //设置显示的金额
                        if(!TextUtils.isEmpty(money)){
                            show_amount.setText(MoneyUtil.formatMoney(money));
                        }
                        if (TextUtils.isEmpty(Stores.stores_name)) {
                            tvShopName.setText("每天惠便利店");
                        } else {
                            Log.v("zyl", "显示店铺名称：" + Stores.stores_name);
                            tvShopName.setText(Stores.stores_name);
                        }
                        createQRImage(data.toString());
                        break;
                    case 4:
                        inputkeyboard.setVisibility(View.GONE);


                        code_interface.setVisibility(View.VISIBLE);
                        //完成按键显示
                        //achieve.setVisibility(View.VISIBLE);
                        if(progressBar!=null){
                            progressBar.dismiss();
                        }

                        if (downtimer != null) {
                            downtimer.start();//开始倒计时
                            time = allTime;
                        }
                        break;
                    default:
                        break;
                }
            }
        };


        payee_amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    submit.setBackgroundResource(R.drawable.border5px_blue_00c3e2);
                    submit.setTextColor(Color.parseColor("#ffffff"));
                } else {
                    submit.setBackgroundResource(R.drawable.border_gray_80ffffff);
                    submit.setTextColor(Color.parseColor("#333333"));
                }
            }
        });


    }

    //如果收款成功，会得到通知
    private void onEvent(EventType1 eventBean) {
        Log.v("zyl", "收到onEvent");
        //比较安全码，如果一样，代表成功
        Log.v("zyl", "eventBean.getSecurity_code():" + eventBean.getSecurity_code());
        if (stringList.contains(eventBean.getSecurity_code())) {
            code_interface.setVisibility(View.GONE);
            CWToast.makeText(PaymentActivity.this, eventBean.getEXTRA_MESSAGE(), Toast.LENGTH_LONG, true)
                    .setToastType(CWToast.TOAST_TYPE_ALERT).show();
            finish();
        }
    }

    private void input_digit(String digit) {
        money = payee_amount.getText().toString();
        if (money.indexOf(".") != -1) {
            //获取小数点的位置
            int num = 0;
            num = money.indexOf(".");
            if (money.length() - num > 2) {
            } else {
                money = money + digit;
            }
        } else {
            money = money + digit;
        }
        payee_amount.setText(money);
    }

    // 要转换的地址或字符串,可以是中文
    public void createQRImage(String url) {
        try {
            // 判断URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return;
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            // 显示到一个ImageView上面
            two_dimension.setImageBitmap(bitmap);
            handler.sendEmptyMessage(4);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAfinalFail() {
        if (progressBar != null) {
            progressBar.dismiss();
        }
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                flow_no = data.getString("flow_no");
                security_code = data.getString("security_code");
                stringList.add(flow_no);
                stringList.add(security_code);
                handler.sendEmptyMessage(3);
            } catch (Exception e) {
            }
        } else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String transaction_status = jsonObject.getString("transaction_status");
                if (transaction_status.equals("completed")) {
                    ToastTools.showShort(PaymentActivity.this, "收款成功");
//                    finish();
                }
            } catch (Exception e) {

            }
        } else if (requestId == 3) {

            try {
                JSONObject jsonObject = new JSONObject(result);
                String transaction_status = jsonObject.getString("   ");
                if (transaction_status.equals("completed")) {
                    ToastTools.showShort(PaymentActivity.this, "收款成功");
//                    finish();
                }
            } catch (Exception e) {

            }
        }
        if (progressBar != null) {
            progressBar.dismiss();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (downtimer != null) {
            downtimer.cancel();
            downtimer.onFinish();
            downtimer = null;
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {

        if (progressBar != null) {
            progressBar.dismiss();
        }
        if (requestId == 1) {
            ToastTools.showShort(PaymentActivity.this, msg);
        } else if (requestId == 3) {
            ToastTools.showShort(PaymentActivity.this, "二维码已失效");
            finish();
        }
    }


    private void initView() {
        tv_bottom_canel = (TextView) findViewById(R.id.tv_bottom_canel);
        tv_bottom_canel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downtimer != null) {
                    downtimer.cancel();
                    downtimer.onFinish();
                }
                finish();

            }
        });
    }
}
